/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the recruit4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.tjmc.recruit.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tjmc.recruit.admin.api.entity.PlatformUserInfoEntity;
import com.tjmc.recruit.admin.api.entity.SysSmsConfEntity;
import com.tjmc.recruit.admin.api.entity.SysUser;
import com.tjmc.recruit.admin.mapper.PlatformUserInfoMapper;
import com.tjmc.recruit.admin.mapper.SysUserMapper;
import com.tjmc.recruit.admin.service.SysMobileService;
import com.tjmc.recruit.admin.service.SysSmsConfService;
import com.tjmc.recruit.common.core.config.SmsConfig;
import com.tjmc.recruit.common.core.constant.CacheConstants;
import com.tjmc.recruit.common.core.constant.SecurityConstants;
import com.tjmc.recruit.common.core.constant.enums.SmsSendTypeEnum;
import com.tjmc.recruit.common.core.exception.ErrorCodes;
import com.tjmc.recruit.common.core.util.AliSmsUtil;
import com.tjmc.recruit.common.core.util.MsgUtils;
import com.tjmc.recruit.common.core.util.R;
import io.springboot.sms.SmsProperties;
import io.springboot.sms.core.SmsClient;
import io.springboot.sms.core.SmsTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lengleng
 * @date 2018/11/14
 * <p>
 * 手机登录相关业务实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysMobileServiceImpl implements SysMobileService {

    private final RedisTemplate redisTemplate;

    private final SysUserMapper userMapper;

    private final PlatformUserInfoMapper platformUserInfoMapper;

    private final SysSmsConfService sysSmsConfService;

    /**
     * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
     *
     * @param mobile mobile
     * @return code
     */
    @Override
    public R<Boolean> sendSmsCode(String mobile, Boolean isLogin) {
        if (isLogin){
            //登录用途需判断是否已经注册
            List<SysUser> userList = userMapper
                    .selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, mobile));
            List<PlatformUserInfoEntity> platUserList = platformUserInfoMapper
                    .selectList(Wrappers.<PlatformUserInfoEntity>query().lambda().eq(PlatformUserInfoEntity::getPhone, mobile));
            if (CollUtil.isEmpty(userList) && CollUtil.isEmpty(platUserList)) {
                log.info("手机号未注册:{}", mobile);
                return R.ok(Boolean.FALSE, MsgUtils.getMessage(ErrorCodes.SYS_APP_PHONE_UNREGISTERED, mobile));
            }
        }

        Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + mobile);

        if (codeObj != null) {
            log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
            return R.ok(Boolean.FALSE, MsgUtils.getMessage(ErrorCodes.SYS_APP_SMS_OFTEN));
        }
        //查询验证码短信配置信息
        List<SysSmsConfEntity> confEntityList = sysSmsConfService.list(new LambdaQueryWrapper<SysSmsConfEntity>()
                .eq(SysSmsConfEntity::getType, "VAL")
                .eq(SysSmsConfEntity::getStatus, "0"));
        if (CollUtil.isEmpty(confEntityList)) {
            return R.failed("未查询到短信配置");
        }
        SysSmsConfEntity sysSmsConfEntity = confEntityList.get(0);

        String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
        log.debug("手机号生成验证码成功:{},{}", mobile, code);
        redisTemplate.opsForValue()
                .set(CacheConstants.DEFAULT_CODE_KEY + mobile, code, sysSmsConfEntity.getValTime(), TimeUnit.SECONDS);
        //发送短信
        SmsConfig smsConfig = new SmsConfig();

        smsConfig.setTemplateCode(sysSmsConfEntity.getSmsCode());
        smsConfig.setAccessId(sysSmsConfEntity.getAccessKeyId());
        smsConfig.setAccessKey(sysSmsConfEntity.getAccessKeySecret());
        smsConfig.setSignName(sysSmsConfEntity.getSingName());
        JSONObject object = new JSONObject();
        object.put("code", code);
        AliSmsUtil.send(smsConfig, mobile, object.toJSONString());
        return R.ok(Boolean.TRUE);
    }

}
